﻿using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class DeleteProcessinfoHandler:IRequestHandler<DeleteProcessinfoCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<Processinfo> _processRepository;
        private ILogger<DeleteProcessinfoHandler> _logger;

        public DeleteProcessinfoHandler(IProcessRepository<Processinfo> processRepository, ILogger<DeleteProcessinfoHandler> logger)
        {
            _processRepository = processRepository;
            _logger = logger;
        }
        /// <summary>
        /// 删除工序数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async  Task<ApiResult<int>> Handle(DeleteProcessinfoCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var query =_processRepository.GetAllAsync().FirstOrDefault(x=>x.Id==request.Id && !x.IsDelete);
            if (query != null)
            {
                query.IsDelete = true;
            }
            var res = _processRepository.UpdateAsync(query).Result;
            if(res>0)
            {
                _logger.LogInformation("删除工序数据成功");
                result.Code=ErrorStatus.Success;
                result.Message = "删除工序数据成功";
                result.Data = res;  
            }
            else
            {
                _logger.LogError("删除工序数据失败");
                result.Code = ErrorStatus.Error;
                result.Message = "删除工序数据失败";
                result.Data = res;
            }
            return result;
        }
    }
}
